<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="字辈名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          type="success"
          icon="plus"
          @click="handleOpenDialog()"
        >
          新增
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="generationTableData"
        highlight-current-row
        @row-click="handleRowClick"
      >
        <el-table-column label="字辈名称" prop="name" min-width="120" />
        <el-table-column label="字辈排序" prop="order" align="center" width="100" />
        <el-table-column label="字辈含义" prop="meaning" min-width="200" />
        <el-table-column label="创建时间" prop="createTime" width="160" />
        <el-table-column label="备注" prop="remark" min-width="150" />
        <el-table-column fixed="right" align="center" label="操作" width="180">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      :size="drawerSize"
      @close="handleCloseDialog"
    >
      <el-form ref="generationFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="字辈名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入字辈名称" />
        </el-form-item>

        <el-form-item label="字辈排序" prop="order">
          <el-input-number
            v-model="formData.order"
            :min="1"
            controls-position="right"
            placeholder="请输入字辈排序"
          />
        </el-form-item>

        <el-form-item label="字辈含义" prop="meaning">
          <el-input
            v-model="formData.meaning"
            type="textarea"
            placeholder="请输入字辈含义"
            :rows="3"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { useAppStore } from "@/store/modules/app.store";
import { DeviceEnum } from "@/enums/settings/device.enum";

defineOptions({
  name: "Generation",
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryFormRef = ref();
const generationFormRef = ref();

const loading = ref(false);
const dialog = reactive({
  title: "新增字辈",
  visible: false,
});

const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "500px" : "90%"));

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keywords: "",
});

// 分页总数
const total = ref(0);

// 字辈表格数据
const generationTableData = ref([]);

// 选中的行ID
const selectedGenerationId = ref();

// 初始表单数据
const initialFormData = ref({
  id: undefined,
  name: "",
  order: 1,
  meaning: "",
  remark: "",
});

// 表单数据
const formData = ref({ ...initialFormData.value });

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: "请输入字辈名称", trigger: "blur" }],
  order: [{ required: true, message: "请输入字辈排序", trigger: "blur" }],
});

// 查询字辈列表
function handleQuery() {
  loading.value = true;
  // 假设这里有一个 API 调用
  // GenerationAPI.getList(queryParams)
  //   .then((res) => {
  //     generationTableData.value = res.data;
  //     total.value = res.total;
  //   })
  //   .finally(() => {
  //     loading.value = false;
  //   });
  
  // 模拟数据
  setTimeout(() => {
    generationTableData.value = [
      {
        id: "1",
        name: "德",
        order: 1,
        meaning: "品德高尚，为人正直",
        remark: "第一世字辈",
        createTime: "2023-01-01 12:00:00"
      },
      {
        id: "2",
        name: "明",
        order: 2,
        meaning: "明理通达，聪慧过人",
        remark: "第二世字辈",
        createTime: "2023-01-02 12:00:00"
      },
      {
        id: "3",
        name: "善",
        order: 3,
        meaning: "善良淳朴，乐于助人",
        remark: "第三世字辈",
        createTime: "2023-01-03 12:00:00"
      }
    ];
    total.value = 3;
    loading.value = false;
  }, 500);
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

// 处理每页条数变化
function handleSizeChange(size) {
  queryParams.pageSize = size;
  handleQuery();
}

// 处理页码变化
function handleCurrentChange(page) {
  queryParams.pageNum = page;
  handleQuery();
}

// 行点击事件
function handleRowClick(row) {
  selectedGenerationId.value = row.id;
}

// 打开表单弹窗
function handleOpenDialog(id) {
  if (id) {
    dialog.title = "编辑字辈";
    // GenerationAPI.getFormData(id).then((data) => {
    //   initialFormData.value = { ...data };
    //   formData.value = data;
    // });
    
    // 模拟获取数据
    const found = generationTableData.value.find(item => item.id === id);
    if (found) {
      initialFormData.value = { ...found };
      formData.value = { ...found };
    }
  } else {
    dialog.title = "新增字辈";
    resetForm();
  }
  dialog.visible = true;
}

// 提交表单
function handleSubmit() {
  generationFormRef.value.validate((isValid) => {
    if (isValid) {
      const id = formData.value.id;
      if (id) {
        // GenerationAPI.update(id, formData.value).then(() => {
        //   ElMessage.success("修改成功");
        //   handleCloseDialog();
        //   handleQuery();
        // });
        
        // 模拟更新
        ElMessage.success("修改成功");
        handleCloseDialog();
        handleQuery();
      } else {
        // GenerationAPI.create(formData.value).then(() => {
        //   ElMessage.success("新增成功");
        //   handleCloseDialog();
        //   handleQuery();
        // });
        
        // 模拟新增
        ElMessage.success("新增成功");
        handleCloseDialog();
        handleQuery();
      }
    }
  });
}

// 删除字辈
function handleDelete(id) {
  if (!id) {
    ElMessage.warning("请选择要删除的字辈");
    return;
  }

  ElMessageBox.confirm("确认删除该字辈吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      // GenerationAPI.deleteById(id)
      //   .then(() => {
      //     ElMessage.success("删除成功");
      //     handleQuery();
      //   })
      //   .finally(() => {
      //     loading.value = false;
      //   });
      
      // 模拟删除
      setTimeout(() => {
        ElMessage.success("删除成功");
        handleQuery();
        loading.value = false;
      }, 500);
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 重置表单
function resetForm() {
  if (generationFormRef.value) {
    generationFormRef.value.resetFields();
    generationFormRef.value.clearValidate();
  }
  formData.value = {
    id: undefined,
    name: "",
    order: 1,
    meaning: "",
    remark: "",
  };
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>
